package com.golxen.framework.common.server.agent.cmd;


import com.golxen.framework.AgentProtocol;
import com.golxen.framework.ClientProtocol;
import com.golxen.framework.GameProtocol;
import com.golxen.framework.PBPacket.PBPacket;
import com.golxen.framework.PBPacket.PBPacketUtils;
import com.golxen.framework.common.server.agent.AgentPlayer;
import com.golxen.framework.common.server.agent.AgentPlayerMgr;
import com.golxen.framework.common.server.game.cmd.Cmd;
import com.golxen.framework.common.server.game.cmd.Command;
import com.golxen.protojava.CommonProto;
import com.golxen.protojava.LoginProto;
import com.golxen.utils.LogUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

@Cmd(code = AgentProtocol.A_LOGIN_RESPONSE, desc = "GameServer返回是否允许用户登录")
public class LoginResultCmd implements Command {

	@Override
	public Tuple execute(ChannelHandlerContext ctx, PBPacket packet) throws Exception {
		LoginProto.LoginResultMsg msg = LoginProto.LoginResultMsg.parseFrom(packet.toByteArray());
		boolean result = msg.getResult();
		long userId = msg.getUserId();

		LogUtil.COMMON.info("[loginmark] agent login {} {}", userId, result);

		AgentPlayer player = AgentPlayerMgr.getOnlineUser(userId);
		Channel channel = AgentPlayerMgr.removeTempChannel(userId);
		if (null == channel) {
			LogUtil.COMMON.warn("Login result failed, client channel is null, userId = " + userId);

			LogUtil.COMMON.info("[loginmark] agent login {} {} {}", userId, result, "channel is null");
			return new Tuple(null, msg);
		}

		LogUtil.COMMON.info("[loginmark] agent login {} {} {}", channel.id().asShortText(), userId, result);
		if (!result) {
			LogUtil.COMMON.error("user waite failed ressult={}, userId = {} close channel", result, userId);
			channel.close().addListener(f -> {
				LogUtil.COMMON.error("user waite failed ressult={}, userId = {} close channel done", result, userId);
			});
			return new Tuple(null, msg);
		}

		try {
			if (null != player && player.getMyChannel() != null) {
				Channel ch = player.getChannel();
				try {
					PBPacket buildMessage = PBPacketUtils.buildMessage(ClientProtocol.U_OTHER_LOGIN_YOUR_ROLE,
							player.getUserId(), CommonProto.NullValueMsg.newBuilder());

					ch.writeAndFlush(buildMessage).addListener(ChannelFutureListener.CLOSE);
				} catch (Exception ex) {
					LogUtil.COMMON.error("", ex);
				}

			}
		} catch (Exception e) {
			LogUtil.COMMON.error("Disconnect userId = " + player.getUserId());
		}

		AgentPlayerMgr.addOnline(userId, channel);

		return new Tuple(null, msg);
	}

}
